package com.mspbots.attendance.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/websocket/{userId}")
@Component
@Slf4j
public class AttendanceWebsocketServer {
    /**
     * user map
     */
    private static Map<String, Session> clients = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        log.debug("new user: {}", session.getId());
        //add to mapp
        clients.put(session.getId(), session);
    }

    /**
     * client close
     *
     * @param session session
     */
    @OnClose
    public void onClose(Session session) {
        log.debug("user close:{}", session.getId());
        //remove session from map
        clients.remove(session.getId());
    }

    /**
     * on error
     *
     * @param throwable e
     */
    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }

    /**
     * onMessage
     *
     * @param message
     */
    @OnMessage
    public void onMessage(String message) {
        log.debug("get message from client: {}", message);
        this.sendAll(message);
    }

    /**
     * sendAll
     *
     * @param message
     */
    public void sendAll(String message) {
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            sessionEntry.getValue().getAsyncRemote().sendText(message);
        }
    }

}
